/**
 * Developer : aOmMiez
 * Date : 4/9/13 AD
 * Time : 12:28 PM
 * File : signup.js
 */

var signup = function(){};

signup.prototype.init = function(req, res){
    if(req.route.method == 'get') {
        this.signup(req, res);
    }
    else if(req.route.method == 'post') {
        this.signup(req, res);
    }
    else if(req.route.method == 'put') {
        // put method
    }
    else if(req.route.method == 'delete') {
        // delet method
    }
};

signup.prototype.signup = function(req, res){
    var email = req.param('email');
    var password = req.param('password');
    var name = req.param('name');
    var token = components.string.genToken();
    var agentId;
    var data = {};
    GLOBAL.Mysql.query("SELECT id FROM Account WHERE email = "+Mysql.escape(email),function(err,resMySql){
        if ( err ) {
        	throw new Exception(9999, 'Mysql Error: '+err, function(){
        		console.log('Mysql Error: '+err);
        		res.send(this.toString());
            	res.end();
        	});
        } else {
            console.log(resMySql);
            if ( resMySql.length > 0 ) {
                throw new Exception ( 9999 , 'email have to use it.' ,function(){
                	console.log('Mysql Error: '+err);
                    res.send(this.toString());
                    res.end();
                });
            } else {
                GLOBAL.Mysql.query("INSERT INTO Account (name,email,password) VALUES ('"+name+"','"+email+"','"+components.string.encryptPassword(password)+"')" ,function(errInsert,resInsert){
                    if (err) {
                    	throw new Exception(9999, 'Mysql Error: '+err, function(){
			        		console.log('Mysql Error: '+err);
			        		res.send(this.toString());
			            	res.end();
			        	});
                    } else {
                        agentId = resInsert.id;
                        GLOBAL.Mysql.query("INSERT INTO AccessToken (agentId,token) VALUES ('"+agentId+"','"+token+"')",function(errInsertToken,resInsertToken){
                            if (err) {
                            	throw new Exception(9999, 'Mysql Error: '+errInsertToken, function(){
					        		console.log('Mysql Error: '+errInsertToken);
					        		res.send(this.toString());
					            	res.end();
					        	});
                            } else {
                                console.log(resInsertToken);
                                data.id = agentId;
                                data.email = email;
                                data.name = name;
                                data.token = token;
                                res.send(JSON.stringify(data));
                                res.end();
                            }
                        });
                    }
                });

            }
        }
    });
};

module.exports = signup;